package org.jimi.test.plugin.handlers;


import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.viewers.IStructuredSelection;
//import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.core.resources.IFile;
import org.eclipse.epsilon.common.util.FileUtil;
import org.eclipse.epsilon.egl.EglFileGeneratingTemplateFactory;
import org.eclipse.epsilon.egl.incremental.EgxModuleInc;
import org.eclipse.epsilon.egl.exceptions.EglRuntimeException;
import org.eclipse.epsilon.eol.exceptions.EolRuntimeException;
import org.eclipse.epsilon.eol.exceptions.models.EolModelLoadingException;
import org.eclipse.epsilon.eol.execute.context.Variable;
import org.jimi.test.plugin.Activator;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.epsilon.emc.emf.EmfModel;


/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class SampleHandler extends AbstractHandler {
	public static String project_path;
	public static String outputRoot;
	public static String projectName;
	public static String workspace;
	public static String sourcePath;
	public static String fileName;
	/**
	 * The constructor.
	 */
	public SampleHandler() {
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		
		ISelectionService service = window.getSelectionService();
		
		IStructuredSelection structured = (IStructuredSelection) service.getSelection();
		
		if(structured.getFirstElement() instanceof IFile){
			IFile file = (IFile) structured.getFirstElement();
			IPath path = file.getLocation();
			outputRoot = file.getProject().getLocation().toString();
			
			projectName = file.getProject().getFullPath().toString();
			System.out.println(projectName);
			
			sourcePath = projectName.replace('.', '/');
			
			workspace = outputRoot.replaceAll(projectName, "");
			
			fileName = path.lastSegment().toString().replaceAll(".ecore", "");
			project_path = path.toString();
			//System.out.println("project path: " + project_path);
			
			try {
				file.getWorkspace().getRoot().getProject(projectName + ".graphiti").create(null);
				file.getWorkspace().getRoot().getProject(projectName + ".graphiti").open(null);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
		
		EmfModel model = new EmfModel();
        model.setName("ECore");
        EPackage.Registry.INSTANCE.put(EcorePackage.eINSTANCE.getNsURI(), EcorePackage.eINSTANCE);
        model.setMetamodelUri(EcorePackage.eINSTANCE.getNsURI());
        model.setModelFile(project_path);
        //model.setModelFile(file.getAbsolutePath());
        try {
			model.load();
		} catch (EolModelLoadingException e1) {
			e1.printStackTrace();
		}
		
        EglFileGeneratingTemplateFactory templateFactory = new EglFileGeneratingTemplateFactory();
        
        try {
			templateFactory.setOutputRoot(outputRoot + ".graphiti/src/");
			//System.out.println(outputRoot + ".graphiti" + "/src/");
		} catch (EglRuntimeException e1) {
			e1.printStackTrace();
		}
		
        
		EgxModuleInc template = new EgxModuleInc(templateFactory);
		try {
			template.parse(Activator.getDefault().getBundle().getResource("src/templates/test.egx").toURI());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// You'll need to loop over the list returned by this method, and
		// log any errors somewhere.
		System.out.println(template.getParseProblems().toString());
		
		//template.populate("projectName", projectName);
		template.getContext().getFrameStack().put(Variable.createReadOnlyVariable("project_path", project_path));
		template.getContext().getFrameStack().put(Variable.createReadOnlyVariable("sourcePath", sourcePath));
		template.getContext().getFrameStack().put(Variable.createReadOnlyVariable("project_name", projectName+".graphiti"));
		template.getContext().getFrameStack().put(Variable.createReadOnlyVariable("workspace", workspace));
		template.getContext().getModelRepository().addModel(model);
		
		long startTime = System.nanoTime();
		try {
			startTime = System.nanoTime();
			template.execute();
		} catch (EolRuntimeException e) {
			e.printStackTrace();
		}
		long endTime = System.nanoTime();
		System.out.println("Time: " + (endTime-startTime)/1000000000.0);
		return null;
	}
}
